package cn.moon.server.channel;

import cn.moon.protocol.ProxyMessage;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 信道管理器
 */
public class ServerChannelManager {

    /**
     * 桥信道
     */
    private Channel bridgeChannel;

    /**
     * 桥信道id
     */
    private String bridgeChannelId;


    /**
     * 接入信道
     */
    private final ConcurrentHashMap<String, Channel> portalChannels = new ConcurrentHashMap<>();


    private static final ServerChannelManager instance = new ServerChannelManager();

    private ServerChannelManager (){}


    /**
     * 保存桥信道
     * @param channel 桥信道
     */
    public static void setBridgeChannel(Channel channel) {
        instance.bridgeChannel = channel;
        instance.bridgeChannelId = channel.id().asLongText();
    }

    public static void removeBridgeChannel(Channel channel){
        if(channel.id().asLongText().equals(instance.bridgeChannelId)){
            instance.bridgeChannel = null;
        }
    }

    public static void addPortalChannel(Channel channel) {

        instance.portalChannels.put(channel.id().asLongText(), channel);

    }

    public static void removePortalChannel(Channel channel){

        instance.portalChannels.remove(channel.id().asLongText());

    }

    public static void bridgeChannelForward(ProxyMessage proxyMessage){

        if(instance.bridgeChannel != null && instance.bridgeChannel.isActive()){
            instance.bridgeChannel.writeAndFlush(proxyMessage);
        }
    }

    public static void portalChannelForward(String channelId, byte[] data){

        Channel channel = instance.portalChannels.get(channelId);

        if(channel != null){
            channel.writeAndFlush(Unpooled.wrappedBuffer(data));
        }
    }

}
